<template>
  <!-- 添加或修改设备对话框 -->
  <el-dialog
    :title="title"
    :visible.sync="open"
    append-to-body
    :modal="false"
    top="74px"
    class="container-dailog transition-box"
    :class="$store.state.app.sidebar.opened ? 'openSidebar' : 'hideSidebar'"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      <div class="border padding-lr-20 padding-top-20">
        <div class="text-12">基本信息</div>
        <div class="flex margin-top-10">
          <div>
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
            </el-form-item>
            <el-form-item label="所属组织" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择组织"
              />
            </el-form-item>
            <el-form-item label="设备编号" prop="deviceNum">
              <el-input v-model="form.deviceNum" placeholder="请输入设备编号" />
            </el-form-item>
            <el-form-item label="从机地址" prop="slaveAddress">
              <el-input v-model="form.slaveAddress" placeholder="请输入从机地址" />
            </el-form-item>
            <el-form-item label="设备描述" prop="deviceDesc">
              <el-input type="textarea" v-model="form.deviceDesc" placeholder="请输入设备描述1" />
            </el-form-item>
          </div>
          <div>
           <el-form-item label="上传图片">
              <el-upload  :action="uploadImgUrl"
                          :headers="headers"
                          :on-success="handleSuccess"
                          :on-error="handleError"
                          :before-upload="beforeUpload"
                          :limit="1">
                <el-button size="small" type="primary">选择文件</el-button>
              </el-upload>
            </el-form-item> 
            <el-form-item label="设备位置">
              <el-radio-group v-model="form.locationType">
                <el-radio
                  v-for="dict in dict.type.location_type"
                  :key="dict.value"
                  :label="dict.raw.dictCode"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="设备地图">
              {{ form.addr }}<el-button type="primary" plain @click="openMapHandle">地图</el-button>
            </el-form-item>
          </div>
        </div>
      </div>
      <div class="border padding-lr-20 padding-top-20 margin-top-20">
        <div class="text-12">数据设置</div>
        <div class="flex margin-top-10">
          <el-form-item label="关联设备模板" prop="templatesId">
            <el-select v-model="form.templatesId" placeholder="请选择关联模板"> 
              <el-option
                v-for="item in templates"
                :key="item.id"
                :label="item.templatesName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
      </div>
      <div class="border padding-lr-20 padding-top-20 margin-top-20">
        <div class="text-12">联网设置</div>
        <div class="flex margin-top-10">
          <el-form-item label="关联的网关" prop="gatewayId">
            <el-select v-model="form.gatewayId" placeholder="请选择关联模板"> 
              <el-option
                v-for="item in gateways"
                :key="item.id"
                :label="item.gatewayName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <!-- 地图弹窗 -->
    <el-dialog :visible.sync="mapObj.show" width="40%" top="20px" title="地图" append-to-body>
      <div class="map">
        <el-autocomplete
          v-model.trim="mapObj.search"
          :fetch-suggestions="mapQuerySearch"
          placeholder="请输入详细地址"
          style="width: 100%"
          :trigger-on-focus="false"
          @select="handleSelect"
          class="map-autocomplete"
        />
        <baidu-map
          class="map-container"
          :zoom="15"
          :center="mapObj.cneter"
          inertial-dragging
          @click="paintPolyline"
          :scroll-wheel-zoom="true"
          @ready="handlerBMap"
        >
          <bm-marker :position="mapObj.marker" :dragging="false">
          </bm-marker>
        </baidu-map>
        <el-form label-position="top" class="padding-20 bg-gray">
          <el-form-item label="详细地址" prop="addr">
            <el-input v-model="mapObj.addr" type="text" />
          </el-form-item>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="经度" prop="lng">
                <el-input :disabled="mapObj.disabled" v-model="mapObj.lng" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="纬度" prop="lat">
                <el-input :disabled="mapObj.disabled" v-model="mapObj.lat" type="text" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="操作">
                <el-button v-if="mapObj.disabled" @click="editLngLatHandle" type="primary" icon="el-icon-edit" circle></el-button>
                <template v-else>
                  <el-button @click="cancelLngLatHandel">取消</el-button>
                  <el-button @click="saveLngLatHandel" type="primary">保存</el-button>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="mapSubmitForm">确 定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import { getLocation } from "@/utils/map.js"
  import { listTemplates } from "@/api/iot/templates";
  import { listGateway } from "@/api/iot/gateway";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { addDevice, updateDevice } from "@/api/iot/device";
  import { BaiduMap, BmMarker } from "vue-baidu-map";
  import { getToken } from "@/utils/auth";

  export default {


    name: "device-form-dialog",
    components: { Treeselect, BaiduMap, BmMarker },
    dicts: ["location_type"],
    props: {
      supThis: {
        type: Object,
        default: null,
      },
      deptOptions: {
        type: Array,
        default: () => [],
      }
    },
    data() {
      return {
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          deviceName: [
            { required: true, message: "设备名称不能为空", trigger: "blur" },
          ],
          deptId: [
            { required: true, message: "所属组织id不能为空", trigger: "blur" },
          ],
        },
        // 模板列表
        templates: [],
        // 网关列表
        gateways: [],
        // 地图参数
        mapObj: {
          show: false,
          addr: null,
          lng: null,
          lat: null,
          cneter: null,
          disabled: true,
          marker: null,
          defaultLocation: [],
          search: null
        },
        BMap: null,
        map: null,
        uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
        headers: { Authorization: "Bearer " + getToken(),
        fileName: null,
      },
      }
    },
    mounted() {
      this.getTemplateList()
      this.getGatewayList()
    },
    methods: {
      async handlerBMap({ BMap, map }) {
        this.BMap = BMap;
        this.map = map;
      },
      handleSelect(item) {
        this.makerCenter(item.point)
        this.mapObj.addr = item.value;
        this.mapObj.lng = item.point.lng;
        this.mapObj.lat = item.point.lat;
        this.mapObj.search = ''
      },
      mapQuerySearch(queryString, cb) {
        var that = this;
        var myGeo = new this.BMap.Geocoder();
        myGeo.getPoint(
          queryString,
          function(point) {
            if (point) {
              that.coordinate = point;
              that.makerCenter(point);
            } else {
              that.coordinate = null;
            }
          },
          this.locationCity
        );
        var options = {
          onSearchComplete: function(results) {
            if (local.getStatus() === 0) {
              // 判断状态是否正确
              var s = [];
              for (var i = 0; i < results.getCurrentNumPois(); i++) {
                var x = results.getPoi(i);
                var item = { value: x.address + x.title, point: x.point };
                s.push(item);
                cb(s);
              }
            } else {
              cb();
            }
          },
        };
        var local = new this.BMap.LocalSearch(this.map, options);
        local.search(queryString);
      },
      makerCenter(point) {
        if (this.map) {
          this.map.clearOverlays();
          this.map.addOverlay(new this.BMap.Marker(point));
          this.mapObj.lng = point.lng;
          this.mapObj.lat = point.lat;
          this.mapObj.cneter= { lng: point.lng, lat: point.lat }
        }
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          deviceName: null,
          deptId: null,
          deviceNum: null,
          deviceStatus: null,
          deviceDesc: null,
          locationType: null,
          lng: null,
          lat: null,
          templatesId: null,
          gatewayId: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
        };
        this.getLocation()
        this.resetForm("form");
      },
      // 获取模板列表
      getTemplateList() {
        listTemplates({
          pageNum: 1,
          pageSize: 999
        }).then((response) => {
          this.templates = response.rows;
        });
      },
      getGatewayList() {
        listGateway({
          pageNum: 1,
          pageSize: 999
        }).then((response) => {
          this.gateways = response.rows;
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.form.deviceImg = this.fileName;
        console.log(this.fileName);
        console.log(this.form);
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id != null) {
              updateDevice(this.form).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.supThis.getList();
              });
            } else {
              addDevice(this.form).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.supThis.getList();
              });
            }
          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 获取当前设备定位
      getLocation() {
        getLocation().then(res => {
          this.form.addr = res.address
          this.form.lng = res.lng
          this.form.lat = res.lat
        })
      },
      // 打开地图dialog
      openMapHandle() {
        this.mapObj.show = true
        this.mapObj.addr = this.form.addr
        this.mapObj.lng = this.form.lng
        this.mapObj.lat = this.form.lat
        const point = new BMap.Point(this.mapObj.lng, this.mapObj.lat)
        this.mapObj.marker = point
        this.mapObj.cneter = point
      },
      // 点击地图
      paintPolyline(e) {
        const point = e.point
        this.inverseLocation(point).then((address) => {
          this.mapObj.addr = address
          this.mapObj.lng = point.lng
          this.mapObj.lat = point.lat
          this.mapObj.marker = point
          this.mapObj.cneter = point
        })
      },
      // 点击修改地图经纬度
      editLngLatHandle() {
        this.mapObj.disabled = false
        this.mapObj.defaultLocation = [this.mapObj.lng, this.mapObj.lat]
      },
      // 取消修改经纬度
      cancelLngLatHandel() {
        this.mapObj.disabled = true
        this.mapObj.lng = this.mapObj.defaultLocation[0]
        this.mapObj.lat = this.mapObj.defaultLocation[1]
        this.mapObj.defaultLocation = []
      },
      // 经纬度逆解析地址
      inverseLocation(point) {
        return new Promise((resolve, reject) => {
          const geoc = new BMap.Geocoder()
          geoc.getLocation(point, (res => {
            resolve(res.address)
          }))
        })
      },
      // 保存修改的经纬度
      saveLngLatHandel() {
        const _this = this
        if (this.mapObj.lng && this.mapObj.lat) {
          const geoc = new BMap.Geocoder()
          const point = new BMap.Point(this.mapObj.lng, this.mapObj.lat)
          this.inverseLocation(point).then((address) => {
            _this.mapObj.addr = address
            _this.mapObj.marker = point
            _this.mapObj.cneter = point
            _this.mapObj.disabled = true
            _this.mapObj.defaultLocation = []
          })
        } else {
          this.$modal.msgError("请选择地图位置")
        }
      },
      // 地图提交
      mapSubmitForm() {
        if (this.mapObj.addr && this.mapObj.lng && this.mapObj.lat) {
          this.form.addr = this.mapObj.addr
          this.form.lng = this.mapObj.lng
          this.form.lat = this.mapObj.lat
          this.mapObj.show = false
        } else {
          this.$modal.msgError("请选择地图位置")
        }
      },

    handleSuccess(response, file, fileList) {
      // 图片上传成功后的处理逻辑
      this.fileName = response.fileName;
      console.log('图片上传成功', response, file, fileList);
    },
    handleError(err, file, fileList) {
      // 图片上传失败后的处理逻辑
      console.error('图片上传失败', err, file, fileList);
    },
    beforeUpload(file) {
      // 上传图片前的校验逻辑
      // const isJPG = file.type === 'image/jpeg';
      const isLT2M = file.size / 1024 / 1024 < 2;
 
      // if (!isJPG) {
      //   this.$message.error('上传图片只能是 JPG 格式!');
      // }
      if (!isLT2M) {
        this.$message.error('上传头像大小不能超过 2MB!');
      }
      // return isJPG && isLT2M;
      return isLT2M;

    }
    },
  }
</script>

<style lang="scss" scoped>
.map-container  {
  width: 100%;
  height: 400px;
}
.map {
  position: relative;
}
.map-autocomplete {
  position: absolute;
  width: 350px !important;
  right: 20px;
  top: 20px;
  z-index: 9;
}
</style>